<?php
use \GatewayWorker\Lib\Gateway;
class PHZ_Member
{

    /**
     * 查询并返回房间内用户的地理位置相距米数以及输出ip地址（距离要判断，ip地址直接展示出来即可）
     * @param $room_id
     * @param $db_connect
     */
    public static function __CalculationLcationANDipaddrss( $room_id , $client_id , $db_connect ){
        $room_info = $db_connect->select('room_player_1,room_player_2,room_player_3')->from('tt_room')->where( "room_id = '". $room_id ."'" )->row();//获取房间信息
        $userInfo  = array();
        $keys      = 1;
        foreach ( $room_info as $key => $value ){
            $uInfo = self::__getFieldBy_ID( $value , 'getByAllField' , $db_connect );
            $userInfo[$keys]['uid']      = $value;
            $userInfo[$keys]['ip']       = $uInfo['ip'];
            $userInfo[$keys]['face']     = $uInfo['face'];
            $userInfo[$keys]['name']     = $uInfo['name'];
            $userInfo[$keys]['latitude']  = $uInfo['latitude'];
            $userInfo[$keys]['longitude'] = $uInfo['longitude'];
            if( $uInfo['latitude'] == 0 || $uInfo['longitude'] == 0 ){
                $userInfo[$keys]['is_local'] = 0;
                $userInfo[$keys]['showtext'] = "IP(". $uInfo['ip'] .") " . '(未开启定位权限)';
            }else{
                $userInfo[$keys]['is_local'] = 1;
                $userInfo[$keys]['showtext'] = "IP(". $uInfo['ip'] .") " . $uInfo['location'];
            }
            $keys++;
        }
        /**********************************************************************************************************/
        $callInfo = array();
        foreach ( $userInfo as $key => $value){if( $value['is_local'] == 1 ){$callInfo[$key] = $value;}}//有定位的才去计算距离
        $dis_1_2 = self::__CalculationLcationANDipaddrss_AOE( $callInfo , 1 , 2 );
        $dis_1_3 = self::__CalculationLcationANDipaddrss_AOE( $callInfo , 1 , 3 );
        $dis_1_4 = self::__CalculationLcationANDipaddrss_AOE( $callInfo , 1 , 4 );
        $dis_2_3 = self::__CalculationLcationANDipaddrss_AOE( $callInfo , 2 , 3 );
        $dis_2_4 = self::__CalculationLcationANDipaddrss_AOE( $callInfo , 2 , 4 );
        $dis_3_4 = self::__CalculationLcationANDipaddrss_AOE( $callInfo , 3 , 4 );
        $localInfo = array();
        if( $dis_1_2 !== false ){ array_push( $localInfo , $dis_1_2 ); }
        if( $dis_1_3 !== false ){ array_push( $localInfo , $dis_1_3 ); }
        if( $dis_1_4 !== false ){ array_push( $localInfo , $dis_1_4 ); }
        if( $dis_2_3 !== false ){ array_push( $localInfo , $dis_2_3 ); }
        if( $dis_2_4 !== false ){ array_push( $localInfo , $dis_2_4 ); }
        if( $dis_3_4 !== false ){ array_push( $localInfo , $dis_3_4 ); }
        /**********************************************************************************************************/
        //输出消息
        if( Gateway::isOnline( $client_id ) == 1 ) {
            $data = array();
            $data['log_md']      = 31;
            $data['user_info']   = $userInfo;
            $data['dis_info']    = $localInfo;
            $data['log_data']    = json_encode( array() );
            Gateway::sendToClient( $client_id , json_encode( $data ) ) ;
        }
    }

    private static function __CalculationLcationANDipaddrss_AOE( $callInfo , $key_1 , $key_2 ){
        $distanceArray = array();
        if( isset($callInfo[$key_1]) && isset($callInfo[$key_2]) ){
            $distance = PM_v::__calDis( $callInfo[$key_1]['latitude'] , $callInfo[$key_1]['longitude'] ,$callInfo[$key_2]['latitude'] ,$callInfo[$key_2]['longitude'] , true );
            if ( $distance >= 3000 ) {
                $disText = ($distance/1000) . "公里";
            } else {
                $disText = $distance . "米";
            }
            $distanceArray['name_1'] = $callInfo[$key_1]['name'];
            $distanceArray['name_2'] = $callInfo[$key_2]['name'];
            $distanceArray['dis']    = $disText;
            return $distanceArray;
        }
        return false;
    }

    /**
     * 更新用户的最新一次开房信息记录（用于后续的开房记录）
     * @param $user_id
     * @param $cj_string
     * @param $db_connect
     * @return mixed
     */
    public static function __updateHis_CJ( $user_id , $cj_string , $db_connect ){
        return $db_connect->update('tt_member')->cols(array( 'his_cj' => $cj_string ))->where('uid=' . $user_id )->query();
    }

    /**
     * 实时查询所有人是否离线了；离线了就给查询人发送每个人的状态
     * @param $room_id
     * @param $client_id
     * @param $db_connect
     * @return bool
     */
    public static function __getUserOffLine( $room_id , $client_id , $db_connect ){
        $room_info = $db_connect->select('*')->from('tt_room')->where( "room_id = '". $room_id ."'" )->row();
        if( $room_info == false || $room_info == null || count( $room_info ) <= 0 ){return false;}
        foreach( $room_info as $key => $value ) {
            if (strstr($key, 'room_player_') != false && $value != 0 ) {
                if( Gateway::isUidOnline( $value ) == 0 ){
                    $data = array();
                    $data['log_uid']     = $value;//离线者的用户ID
                    $data['log_md']      = 25;//属于房间内的操作
                    Gateway::sendToClient( $client_id , json_encode( $data ) ) ;
                }else if( Gateway::isUidOnline( $value ) == 1 ){
                    $data = array();
                    $data['log_uid']     = $value;//谁在线？？？
                    $data['log_md']      = 28;//属于房间内的操作
                    Gateway::sendToClient( $client_id , json_encode( $data ) ) ;
                }
            }
        }
    }

    /**
     * 更新用户的config_fail_join参数
     * @param $user_id
     * @param $room_id
     * @param $db_connect
     * @return mixed
     */
    public static function __UserFail_JoinRoom( $user_id , $room_id , $db_connect ){
        $user_info = $db_connect->select('*')->from('tt_member')->where("uid= '". $user_id ."' ")->row();
        $config_fail_join  = $user_info['config_fail_join'] . "," . $room_id;
        return $db_connect->update('tt_member')->cols(array('config_fail_join'=> $config_fail_join ))->where('uid=' . $user_id )->query();
    }

    /**
     * 绑定一次最新的客户端链接ID
     * @param $user_id
     * @param $client_id
     * @param $db_connect
     */
    public static function __BindClient_ID( $user_id , $client_id , $db_connect ){
        $cols = array();
        $cols['last_login_time'] = time();
        $cols['ip']              = $_SERVER["REMOTE_ADDR"];
        $cols['client_id']       = $client_id;
        return $db_connect->update('tt_member')->cols( $cols )->where('uid=' . $user_id )->query();
    }

    /**
     * 如果用户进来了，判断他是否处于某个房间中；给其他三个人发送来线通知
     * @param $room_id
     * @param $user_id
     * @param $db_connect
     */
    public static function __InFoom_sendComeLine( $user_id , $db_connect ){
        //查询当前是否存在正在进行的房间，存在的话；则像其他几个人发送来的信息
        $where     = "room_status = 1 AND (room_player_1 = '".$user_id."' OR room_player_2 = '".$user_id."' OR room_player_3 = '".$user_id."' OR room_player_4 = '".$user_id."')";
        $room_info = $db_connect->select('*')->from('tt_room')->where( $where )->row();
        if( $room_info == false || $room_info == null || count( $room_info ) <= 0 ){return false;}
        //向房间里每个在线的用户离线信息
        foreach( $room_info as $key => $value ) {
            if (strstr($key, 'room_player_') != false && $value != 0 ) {
                $user_clientID = self::__getUserClientID( $value , $db_connect );
                if( $user_clientID != "" && Gateway::isOnline( $user_clientID ) == 1 ){
                    $data = array();
                    $data['log_uid']     = (int)$user_id;//离线者的用户ID
                    $data['log_md']      = 28;//离线的人回来了
                    Gateway::sendToClient( $user_clientID , json_encode( $data ) ) ;
                }
            }
        }
    }

    /**
     * 用户增加钻石
     * @param $user_id
     * @param $consume
     * @param $db_connect
     */
    public static function __UserAdd_consume($user_id , $consume , $db_connect){
        $user_info = $db_connect->select('*')->from('tt_member')->where("uid= '". $user_id ."' ")->row();
        $score = $user_info['score'] + $consume;
        $db_connect->update('tt_member')->cols(array('score'=> $score ))->where('uid=' . $user_id )->query();
    }

    /**
     * 根据用户ID获得client_id
     * @param $user_id
     * @param $db_connect
     */
    public static function __getUserClientID( $user_id , $db_connect ){
        $user_info = $db_connect->select('*')->from('tt_member')->where("uid= '". $user_id ."' ")->row();
        if( $user_info == false || $user_info == null ){
            return "";
        }else{
            return $user_info['client_id'];
        }
    }

    /**
     * 根据client获得用户ID
     * @param $client_id
     */
    public static function __getUserUIDBY_ClientID( $client_id , $db_connect ){
        $user_info = $db_connect->select('*')->from('tt_member')->where("client_id= '". $client_id ."' ")->row();
        if( $user_info == false || $user_info == null ){
            return 0;
        }else{
            return $user_info['uid'];
        }
    }

    /**
     * 通过client_id向用户发送消息
     * @param $user_id    用户ID
     * @param $json_msg   消息主体
     * @param $db_connect 数据库链接
     */
    public static function __adoptClientID_sendMsg( $user_id , $json_msg , $db_connect ){
        return true;
    }

    /**
     * 通过用户ID获取用户的微信信息
     * @param $user_id
     * @param $field
     * @param $db_connect
     */
    public static function __getFieldBy_ID( $user_id , $field , $db_connect ){
        $user_info = $db_connect->select('*')->from('tt_member')->where("uid= '". $user_id ."' ")->row();
        if( $user_info == null || $user_info == false || !isset( $user_info ) ){
            return false;
        }else{
            if( $field == 'getByAllField' ){
                return $user_info;
            }else {
                return $user_info[$field];
            }
        }
    }

    /**
     * 用户是否存在以及获取用户的完整信息，如果不存在则返回false
     * @param $user_id
     */
    public static function __MemberISin_AND_getInfo( $user_id , $db_connect ){
        $user_info = $db_connect->select('*')->from('tt_member')->where("uid= '". $user_id ."' ")->row();
        if( $user_info == false || $user_info == null ){
            return false;
        }else{
            //计算剩余代理天数
            $user_info['proxy_days'] = self::__getMemberProxy_Days( $user_id , $db_connect );
            //返回数据
            return $user_info;
        }
    }

    /**
     * 获取代理剩余天数
     * @param $user_id
     * @param $db_connect
     */
    public static function __getMemberProxy_Days( $user_id , $db_connect ){
        $user_info = $db_connect->select('*')->from('tt_member')->where("uid= '". $user_id ."' ")->row();
        $proxy_days = 0;//默认0天
        if( $user_info['level'] != 0 ){
            $days_time = $user_info['level_et'] - $user_info['level_bt'];
            if( $days_time <= 0 ){//时间差小于等于0，则代表代理已过期
                $proxy_days = 0;
            }else if( $days_time <= 86400 ){//如果小于等于24小时，那就是一天
                $proxy_days = 1;
            }else{
                $proxy_days = ceil( $days_time / 86400 );//天数
            }
        }
        return $proxy_days;
    }

    /**
     * 查询一个用户当前是否正在游戏中,如果正在进行中，则返回房号
     * @info:2017.12.04:若在在游戏中，还需要返回当前用户的最大心跳ID；用于恢复牌局
     * @info:是否游戏判断条件（p1-p4中存在，且房间状态为0或者1的时候，0为房间刚开好；1为游戏进行中）
     * @param $user_id
     * @param $db_connect
     */
    public static function __getMemberISGameing( $user_id , $db_connect , $param3 = "" , $param4 = "" ){
        $game_ing = array(
            'status'  => false,
            'room_id' => 0,
            'max_id'  => 0,
            'config_fail_join' => "",
        );
        $where   = "room_player_1 = " . $user_id;
        $where  .= " or room_player_2 = " . $user_id;
        $where  .= " or room_player_3 = " . $user_id;
        $where  .= " or room_player_4 = " . $user_id;
        $userRoom_info = $db_connect->select('*')->from('tt_room')->where( $where )->query();
        foreach ( $userRoom_info as $key => $value ){
            if( $value['room_status'] == 0 || $value['room_status'] == 1 ){
                $game_ing['status']      = true;//找到存在的房间号
                $game_ing['room_id']     = $value['room_id'];//房间ID
                $game_ing['room_cid']    = $value['room_cid'];//房间创建人
                $game_ing['room_info']   = $value;//房间信息
                $game_ing['max_id']      = PHZ_Card::__get_MAX_HeaderID( $value , $user_id , $db_connect );
                $game_ing['scor_status'] = $value['scor_status'];//结算状态
                $game_ing['log_data']    = PHZ_Log::__getRoomJS_ALLDATA( $value['room_id'] , $value['room_js'] , $user_id , $db_connect );
                $game_ing['card_data']   = PHZ_Card::__get_USER_RoomSignle_Info( $value , $db_connect );
                //当前谁处于吃的状态？ - 吃的牌又是什么
                $eat_card_number         = 0;
                if( $value['tp_card'] >= 1 ){
                    $eat_card_number = $value['tp_card'];
                }else{
                    if( $value['tm_card'] >= 1 ){
                        $eat_card_number = $value['tm_card'];
                    }
                }
                //获取我的牌面信息，以及隐藏底牌跟其他人的牌面数据 + 计算底牌数量
                foreach ( $game_ing['card_data'] as $key_1 => $value_1 ){
                    $game_ing['card_data'][$key_1]['LP']  = PHZ_LiPai::__lipai( $value_1['sp'] , false , $value );
                    $game_ing['card_data'][$key_1]['IDX'] = PHZ_Tools::__get_user_in_room_index( $value , $value_1['uid'] );
                    if( $eat_card_number != 0 ){
                        $game_ing['card_data'][$key_1]['chi_pai'] = PHZ_Chi_Bi_Pai::__chi_pai_bi_pai_chk( $eat_card_number, $value_1['sp'] , $value );//查询用户吃牌信息
                    }
                    //隐藏其他人的手牌信息
                    if( $value_1['uid'] != $user_id ){
                        $game_ing['card_data'][$key_1]['init_sp'] = "";$game_ing['card_data'][$key_1]['sp'] = "";
                        $game_ing['card_data'][$key_1]['LP']      = array();
                    }
                    //隐藏底牌，重算底牌数量
                    $game_ing['card_data'][$key_1]['dp_count'] = count( explode(",", $game_ing['card_data'][$key_1]['dp'] ) );
                    $game_ing['card_data'][$key_1]['dp'] = "";
                }
                //获取用户信息
                $game_ing['member_info'] = self::get_Rec_memberInfo( $value  , $user_id , $db_connect );
                $game_ing['diss_c_time'] = 0;
                //如果当前房间处于解散状态的话;那么实时将倒计时秒数返回
                if( $value['diss_ing'] == 1 ){
                    $game_ing['diss_c_time'] = ($value['diss_time'] + 300) - time();
                }
                //返回详情
                return $game_ing;
                break;
            }
        }
        #.如果没有正在进行房间，把用户的config_fail_join同时返回(前提是用户是这种类型的查询)
        if( $param3 == 'group_join_room' ) {
            $room_info  = PHZ_Room::__getRoomInfo_byID( $param4 , $db_connect );
            $room_error = false;
            if( $room_info == false || $room_info == null ){//游戏不存在或游戏已开始或游戏已结束
                $game_ing['config_fail_join'] = 'roomInfo_error';
                $room_error = true;
            }
            if( $room_info['room_status'] == 1 ){//游戏不存在或游戏已开始或游戏已结束
                $game_ing['config_fail_join'] = 'roomInfo_gameing';
                $room_error = true;
            }
            if( $room_info['room_status'] == 2 ){//游戏不存在或游戏已开始或游戏已结束
                $game_ing['config_fail_join'] = 'roomInfo_over';
                $room_error = true;
            }
            if( $room_error == false ){//房间没错误信息的情况下，再查用户的config_fail_join信息；
                $user_info = $db_connect->select('*')->from('tt_member')->where("uid= '" . $user_id . "' ")->row();
                $game_ing['config_fail_join'] = $user_info['config_fail_join'];
            }
        }
        #.返回结果集
        return $game_ing;
    }

    /**
     * 获取用户牌局恢复的时候，回放信息中的用户信息
     * @param $room_info
     * @param $user_id
     * @param $db_connect
     * @return array
     */
    public static function get_Rec_memberInfo( $room_info , $user_id , $db_connect ){
        $temp = array();
        foreach( $room_info as $key => $value ) {
            if( strstr($key,'room_player_') != false) {
                if( $value != $user_id ){
                    continue;
                }
                $temp['mp'] = $key;//我是几P。。
                $temp['mu'] = $value;
                $temp['mn'] = PHZ_Member::__getFieldBy_ID($value, 'name', $db_connect);
                $temp['mf'] = "";
                $temp['xf'] = "";
                $temp['df'] = "";
                $temp['sf'] = "";
                if( $key == 'room_player_1' ){
                    $temp['xu'] = $room_info['room_player_2'];$temp['xn'] = PHZ_Member::__getFieldBy_ID( $temp['xu'] , 'name' , $db_connect );
                    $temp['su'] = $room_info['room_player_3'];$temp['sn'] = PHZ_Member::__getFieldBy_ID( $temp['su'] , 'name' , $db_connect );
                }else if( $key == 'room_player_2' ){
                    $temp['xu'] = $room_info['room_player_3'];$temp['xn'] = PHZ_Member::__getFieldBy_ID( $temp['xu'] , 'name' , $db_connect );
                    $temp['su'] = $room_info['room_player_1'];$temp['sn'] = PHZ_Member::__getFieldBy_ID( $temp['su'] , 'name' , $db_connect );
                }else if( $key == 'room_player_3' ){
                    $temp['xu'] = $room_info['room_player_1'];$temp['xn'] = PHZ_Member::__getFieldBy_ID( $temp['xu'] , 'name' , $db_connect );
                    $temp['su'] = $room_info['room_player_2'];$temp['sn'] = PHZ_Member::__getFieldBy_ID( $temp['su'] , 'name' , $db_connect );
                }
            }
        }
        return $temp;
    }

}